import request from '@/util/request'
import BASE_URL from '@/util/path'
import Cache from '../util/cache';
import store from '../store'

//小程序授权登录
export function getWxCode() {
	return new Promise((resolve, reject) => {
		uni.login({
			success(res) {
				resolve(res.code);
			},

			fail(res) {
				reject(res);
			}

		});
	});
}


export function getOpenId(data) {
	return request.post('api/auth/wx_verify',data);
}

export async function getloginKey() {
	const code = await getWxCode()
	const { data } = await getOpenId({code:code})
	return data;
}

export function getPhone(data) {
	return request.post('api/auth/login_wx',data);
}

export function getProfession(params) {
	return request.get('api/student/get_profession',{ params });
}

export function getCollege(params) {
	return request.get('api/student/get_college',{ params });
}

export function addStudent(data) {
	return request.post('/api/student/add_student',data);
}

export function getUserInfo(data) {
	return request.post('/api/student/get_student_class',data);
}
//小程序静默登录
export function logout() {
	
	return request.post('/api/auth/logout');
	
}

export function editUser(data) {
	return request.post('/api/student/edit_student_class',data);
}

export function editAvatar(data) {
	return request.post('/api/user/update_avatar',data);
}

export function test() {
	return request.get('/api/auth/profile');
}

export  function changeImg() {
	// 修改头像
	uni.chooseImage({
		count: 1, //默认9
		sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
		sourceType: ['album'], //从相册选择
		success: function(res) {
			let tempFilePaths = res.tempFilePaths;
			uni.showLoading({
				title: '图片上传中...'
			})
			// console.log(uni.getStorageSync('baseUrl'));
			const url = BASE_URL.api + '/api/upload/user_avatar';
			// console.log(_url);
			console.log(url);
			uni.uploadFile({
				url: url, //post请求的地址
				filePath: tempFilePaths[0],
				name: 'file',
				header: {
					'content-type': 'application/json',
					'Authorization': 'Bearer ' + Cache.get("TOKEN")
				},
				success: uploadFileRes => {
					console.log(uploadFileRes);
					//这里要注意，uploadFileRes.data是个String类型，要转对象的话需要JSON.parse一下
					var obj = JSON.parse(uploadFileRes.data);
					let updateData = {
						avatar: obj.data.path,
					}
					editAvatar(updateData).then(res => {
						if (res.status_code == 200) {
							// console.log(res);
							let obj  = store.getters.userInfo;
							obj.avatar = res.data.avatar;
							// console.log(obj);
							store.commit('setUserInfo',obj);
							// Fun(res.data.avatar)
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none'
							})
						}
						uni.hideLoading()
					})
				},
				fail(res) {
					console.log(res);
				}
			});
		}
	});
}